package com.dullfox.sbm.common.auth;

import com.dullfox.sbm.model.SysUser;
import com.dullfox.sbm.common.util.ConstUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Author: zengdy
 * Date: 2018/10/30
 */
@Component
public class AuthManager {

    @Autowired
    private TokenManager tokenManager;

    /**
     * 获取请求体
     */
    public HttpServletRequest getRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes sra = (ServletRequestAttributes) requestAttributes;
        return sra.getRequest();
    }

    /**
     * 登录
     */
    public String signIn(SysUser sysUser) {
        return tokenManager.getToken(sysUser);
    }

    /**
     * 获取该访问用户信息
     */
    public SysUser getUser() {
        String token = getToken();
        if (StringUtils.isBlank(token)) {
            return null;
        }
        return tokenManager.getUserByToken(token);
    }

    /**
     * 刷新该登录用户，延时
     */
    public void refreshUser() {
        String token = getToken();
        if (StringUtils.isNotBlank(token)) {
            tokenManager.refreshUserToken(token);
        }
    }

    /**
     * 注销该访问用户
     */
    public void loginOff() {
        String token = getToken();
        if (StringUtils.isNotBlank(token)) {
            tokenManager.loginOff(token);
        }
    }

    public String getToken() {
        HttpServletRequest request = getRequest();
        String token = request.getHeader(ConstUtil.USER_TOKEN);
        if (StringUtils.isBlank(token)) {
            token = request.getParameter(ConstUtil.USER_TOKEN);
        }
        return token;
    }

}
